import React, { Component } from "react";
import {
  Button,
  Modal,
  Form,
  Drawer,
  Alert,
  Divider,
  Icon,
  Badge,
  Popover,
} from "antd";
import "@/assets/css/settings";
import * as ProductionOrderService from "../../../axios/ProductionOrder";
import * as DingTalkSettingsService from "../../../axios/DingTalkSettings";
import {
  BasicLayout,
  BasicLayoutSearch,
} from "../../../components/BasicLayout";
import {
  BasicPagination,
  isInvalidObject,
  TableCustomize,
  openSuccessModal,
  openModalMessage,
  compareDate,
  compareString,
} from "../../../components/TableCustomize";
import { statusList, workStatusList } from "../../../utils/global";
import SearchForm from "./SearchForm";
import AddForm from "./AddForm";
import ChooseBill from "./ChooseBill";
import PassToStock from "./PassToStock";
import ProductionForm from "./ProductionForm";
import AddForm1 from "./AddForm1";
import AddForm2 from "./AddForm2";
import AddForm3 from "./AddForm3";
import AddForm4 from "./AddForm4";
import PaiGongForm from "./PaiGong";
import { withRouter } from "react-router";
import { withPermission } from "../../../components/withpermission";
const RefreshButton = withPermission(Button, "sync");
const CheckAllButton = withPermission(Button, "plus");
const PGButton = withPermission(Button, "paigong");
const KGButton = withPermission(Button, "kaigong");
const BGButton = withPermission(Button, "baogong");
const SJButton = withPermission(Button, "shenqingshiji");
const ZJButton = withPermission(Button, "shenqingzhijian");
const RKButton = withPermission(Button, "shenqingruku");
const DownLoadButton = withPermission(Button, "download");

class ProductionOrder extends Component {
  state = {
    dataSource: [],
    visible: false,
    visibleChooseBill: false,
    visiblePassToStock: false,
    advanced: false,
    statusList: [],
    workStatusList: [],
    searchItem: {
      department: localStorage.getItem("workShop"),
    },
    modalTitle: "派工",
    formData: {},
    drawerVisible: false,
    drawerVisible1: false,
    drawerTitle: "新增",
    pageSize: 10,
    pageNum: 1,
    total: 0,
    columns: [
      {
        title: "序号",
        dataIndex: "dataIndex",
        align: "center",
        width: 50,
        render: (text, record, index) => (
          <span>
            {(this.state.pageNum - 1) * this.state.pageSize + index + 1}
          </span>
        ),
      },
      {
        title: "批号",
        dataIndex: "batchNo",
        width: 100,
        sorter: (a, b) => compareString(a.batchNo, b.batchNo),
      },

      {
        title: "机型",
        width: 180,
        dataIndex: "model",
        sorter: (a, b) => compareString(a.model, b.model),
      },
      {
        title: "装配部门", // 车间
        width: 100,
        // allowEllipsis: true,
        dataIndex: "department",
        sorter: (a, b) => compareString(a.department, b.department),
      },
      // {
      //   title: '装配机位',
      //   width: 100,
      //   // allowEllipsis: true,
      //   dataIndex: 'assemblePosition',
      //   sorter: (a, b) => compareString(a.assemblePosition, b.assemblePosition)
      // },
      {
        title: "装配进度",
        width: 100,
        // allowEllipsis: true,
        dataIndex: "assembleProcess",
        sorter: (a, b) => compareString(a.assembleProcess, b.assembleProcess),
      },
      {
        title: "试机进度",
        width: 100,
        // allowEllipsis: true,
        dataIndex: "testMachineProcess",
        sorter: (a, b) =>
          compareString(a.testMachineProcess, b.testMachineProcess),
      },
      {
        title: "质检进度",
        width: 100,
        // allowEllipsis: true,
        dataIndex: "qualityCheckProcess",
        sorter: (a, b) =>
          compareString(a.qualityCheckProcess, b.qualityCheckProcess),
      },
      {
        title: "批号状态",
        width: 100,
        dataIndex: "isStates",
        sorter: (a, b) => compareString(a.isStates, b.isStates),
        render: (text, record, index) => {
          let a = this.state.statusList.find((item) => item.id == text);
          if (text == 3 || text == 4) {
            const popoverContent = (
              <div onClick={(e) => e.stopPropagation()}>
                <TableCustomize
                  style={{
                    width: "1440px",
                  }}
                  dataSource={this.state.popoverTableData}
                  columns={this.state.childColumns}
                  loading={this.state.popoverLoading}
                  pagination={false}
                  rowKey={(record) => record.workUniqueType}
                  rowClassName={(record, index) => {
                    return [
                      "editable-row",
                      index % 2 === 0 ? "editable-row" : "editable-row12",
                    ];
                  }}
                />
              </div>
            );
            return (
              <div onClick={(e) => e.stopPropagation()}>
                <Popover
                  onVisibleChange={(visible) =>
                    this.popoverVisibleChange(visible, record)
                  }
                  content={popoverContent}
                  autoAdjustOverflow={false}
                  arrowPointAtCenter={true}
                  title="试机工序"
                  trigger="hover"
                  placement="bottom"
                >
                  <a>{a?.value}</a>
                </Popover>
              </div>
            );
          } else {
            return a?.value;
          }
        },
      },
      {
        title: "装配开始日期",
        width: 150,
        // allowEllipsis: true,
        dataIndex: "assembleStartTime",
        sorter: (a, b) => compareDate(a.assembleStartTime, b.assembleStartTime),
      },
      {
        title: "第一交机日期",
        width: 150,
        dataIndex: "firstDeliveryTime",
        sorter: (a, b) => compareDate(a.firstDeliveryTime, b.firstDeliveryTime),
      },
      {
        title: "第一出机日期",
        width: 150,
        dataIndex: "firstOutputTime",
        sorter: (a, b) => compareDate(a.firstOutputTime, b.firstOutputTime),
      },
      {
        title: "操作",
        width: 200,
        dataIndex: "opts",
        render: (text, record) => (
          <>
            <a onClick={() => this.openTGXX(record)}>特供信息</a>
            <Divider type="vertical" />
            <a onClick={() => this.openTZJS(record)}>图纸检索</a>
            {/* <Divider type="vertical" />
          <a onClick={() => this.kaidan(record)}>开单</a> */}
          </>
        ),
      },
      { dataIndex: "" },
    ],
    selectedRows: [],
    selectedRowKeys: [],
    selectedRowsChild: [],
    selectedRowKeysChild: [],
    detailList: [],
    childColumns: [
      {
        title: "序号",
        dataIndex: "ids",
        align: "center",
        width: 50,
        render: (text, record, index) => <span>{index + 1}</span>,
      },
      {
        title: "工序编码",
        width: 100,
        dataIndex: "procedureCode",
        sorter: (a, b) => compareString(a.procedureCode, b.procedureCode),
      },

      {
        title: "工序名称",
        width: 150,
        dataIndex: "procedureName",
        sorter: (a, b) => compareString(a.procedureName, b.procedureName),
        ellipsis: true,
      },
      {
        title: "装配班组",
        width: 100,
        dataIndex: "groupCode",
        sorter: (a, b) => compareString(a.groupCode, b.groupCode),
        ellipsis: true,
      },
      {
        title: "班组名称",
        width: 120,
        ellipsis: true,
        dataIndex: "groupName",
        sorter: (a, b) => compareString(a.groupName, b.groupName),
      },
      {
        title: "班组长",
        width: 100,
        dataIndex: "groupUserName",
        sorter: (a, b) => compareDate(a.groupUserName, b.groupUserName),
      },
      {
        title: "领料进度",
        width: 100,
        dataIndex: "getMaterialProcess",
        sorter: (a, b) =>
          compareDate(a.getMaterialProcess, b.getMaterialProcess),
      },
      {
        title: "发料进度",
        width: 100,
        dataIndex: "distributeMaterialProcess",
        sorter: (a, b) =>
          compareString(
            a.distributeMaterialProcess,
            b.distributeMaterialProcess
          ),
      },
      {
        title: "收料进度",
        width: 100,
        dataIndex: "receiveMaterialProcess",
        sorter: (a, b) =>
          compareDate(a.receiveMaterialProcess, b.receiveMaterialProcess),
      },
      {
        title: "物料状态",
        width: 100,
        dataIndex: "materialStatus",
        sorter: (a, b) => compareDate(a.materialStatus, b.materialStatus),
        render: (text) => {
          return text == "1" ? (
            <Badge
              status="error"
              text={<span style={{ color: "#f5222d" }}>{"欠料"}</span>}
            />
          ) : text == "0" ? (
            <Badge
              status="success"
              text={<span style={{ color: "#1e8e3e" }}>{"正常"}</span>}
            />
          ) : (
            text
          );
        },
      },
      {
        title: "装配状态",
        width: 100,
        dataIndex: "isStates",
        sorter: (a, b) => compareDate(a.isStates, b.isStates),
        render: (text) => {
          let a = this.state.workStatusList.find((item) => item.id == text);
          return a.id == "0" ? (
            <Badge
              status="default"
              text={<span style={{ color: "#d9d9d9" }}>{a.value}</span>}
            />
          ) : a.id == "2" ? (
            <Badge
              status="warning"
              text={<span style={{ color: "#ffc440" }}>{a.value}</span>}
            />
          ) : a.id == "1" ? (
            <Badge
              status="success"
              text={<span style={{ color: "#1e8e3e" }}>{a.value}</span>}
            />
          ) : a.id === "3" ? (
            <Badge
              color="#1890ff"
              text={<span style={{ color: "#1890ff" }}>{a.value}</span>}
            />
          ) : (
            a.value
          );
        },
      },
      {
        title: "操作",
        width: 280,
        dataIndex: "opts",
        render: (text, record) => (
          <>
            {/* <a onClick={() => this.openDetails(record)}>详情</a>
          <Divider type="vertical" />
          <a onClick={() => this.paigong(record)}>派工</a>
          <Divider type="vertical" />
          <a onClick={() => this.kaigong(record)}>开工</a>
          <Divider type="vertical" />
          <a onClick={() => this.baogong(record)}>报工</a>
          <Divider type="vertical" />
          <a disabled={record.isStates != 1} onClick={() => this.quxiaopaigong(record)}>取消派工</a> */}
            {/* <Divider type="vertical" /> */}
            <a
              disabled={record.isStates != 0}
              onClick={() => this.paigong(record)}
            >
              派工
            </a>
            <Divider type="vertical" />
            <a
              disabled={record.isStates != 1}
              onClick={() => this.kaigong(record)}
            >
              开工
            </a>
            <Divider type="vertical" />
            <a
              disabled={record.isStates != 2}
              onClick={() => this.baogong(record)}
            >
              报工
            </a>
            <Divider type="vertical" />
            <a
              disabled={record.isStates != 1}
              onClick={() => this.quxiaopaigong(record)}
            >
              取消派工
            </a>
          </>
        ),
      },
      { dataIndex: "" },
    ],
    row: [],
    addFrom: [[], []],
    addFrom1: [],
    visible_kaigong: false,
    drawerTitle_kaigong: "开工",
    kaigong_type: 0,
    AssignProductionOrderList: [],
    GroupList: [],
    BatchNoList: [],
    ProcessList: [],
    AssignProductionOrderList_kaigong: [],
    btnLoading: false,
    visible_shiji: false,
    formData_shiji: {},
    dataSource_shiji: [],
    formData_zhijian: {},
    dataSource_zhijian: [],
    visible_zhijian: false,
    formData_ruku: {},
    dataSource_ruku: [],
    visible_ruku: false,
    visible_paigong: false,
    paigongData: {},
    dataSourceAll: [],
    downloadLoadingSon: false,
    addFrom: [],
    options: {},
    formData1: [],
    popoverLoading: true,
    popoverTableData: [],
  };
  componentDidMount() {
    this.setState({ statusList, workStatusList });
    this.init();
    if (this.props.location.data) {
      // console.log(this.props.location.data, 'this.props.location.data');
      // this.setState({ searchItem: this.props.location.data.searchItemFather }, this.fetch)
      this.setState(
        {
          searchItem: this.props.location.data.searchItemFather,
          row: [this.props.location.data.batchNo],
        },
        () => {
          this.fetch();
          // 展开并请求展开后的数据
          this.props.location.data.batchNo &&
            this.onExpand(true, { batchNo: this.props.location.data.batchNo });
        }
      );
    } else {
      this.fetch();
    }
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  // 初始化查询
  init = () => {
    // 派工班组查询
    ProductionOrderService.findGroupAll().then((res) => {
      const addFrom = res.data.data;
      // console.log(addFrom, '派工班组查询');
      let options = [];
      for (let i = 0; i < addFrom.length; i++) {
        let childrens = [];
        for (let j = 0; j < addFrom[i].list.length; j++) {
          childrens.push({
            value:
              addFrom[i].list[j].groupCode + "_" + addFrom[i].list[j].groupName,
            label: addFrom[i].list[j].groupName,
          });
        }
        options.push({
          value: addFrom[i].workShop,
          label: addFrom[i].workShop,
          children: childrens,
        });
      }
      this.setState({
        addFrom,
        options,
      });
    });
    // 派工工序查询
    ProductionOrderService.findProcedureAll().then((res) => {
      console.log(res.data.data, "派工工序查询");
      this.setState({
        formData1: res.data.data,
      });
    });
  };
  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true });
    const { searchItem } = this.state;
    searchItem.pageNum = pageNum;
    searchItem.pageSize = pageSize;
    // console.log(searchItem)
    if (searchItem.department && searchItem.department == "null") {
      console.log("值为null");
      searchItem.department = "";
    }
    ProductionOrderService.findPlanAll(searchItem)
      .then((res) => {
        this.setState({ loading: false });
        if (res.data.data.code !== 200) {
          openModalMessage("warning", res.data.data.msg);
          return;
        }
        this.setState({
          dataSource: res.data.data.data,
          total: res.data.data.total,
          pageNum,
          pageSize,
          selectedRowKeys: [],
          selectedRows: [],
          row: [],
        });
      })
      .catch((err) => {
        openModalMessage("error", err.message);
      });
  };

  popoverVisibleChange = (visible, record) => {
    if (visible) {
      this.setState({
        popoverLoading: true,
      });
      let obj = {
        ...this.state.searchItem,
        ...record,
        pageSize: 1000,
        pageNum: 1,
      };
      ProductionOrderService.findMachineWorkDetailsAll(obj).then((res) => {
        this.setState({
          popoverTableData: res.data.data,
          popoverLoading: false,
        });
      });
    } else {
      this.setState({
        popoverLoading: false,
      });
    }
  };
  // 批号进度刷新
  updateBatchRefresh = () => {
    ProductionOrderService.updateBatchRefresh()
      .then((res) => {
        if (res.data.code == 200) {
          this.fetch();
          openSuccessModal(res.data.msg);
        }
      })
      .catch((err) => {
        openModalMessage("error", err.message);
      });
  };
  //派工
  submitMenu = () => {
    this.formAdd.validateFields((err, value) => {
      if (err) return;
      this.setState({ btnLoading: true });
      const { GroupList, BatchNoList, ProcessList } = this.state;
      if (!GroupList.length) {
        openModalMessage("warning", "请选择批号！");
        this.setState({ btnLoading: false });
        return;
      }
      if (!BatchNoList.length) {
        openModalMessage("warning", "请选择工序！");
        this.setState({ btnLoading: false });
        return;
      }
      if (!ProcessList.length) {
        openModalMessage("warning", "请选择班组！");
        this.setState({ btnLoading: false });
        return;
      }
      let arr = [];
      for (var item of GroupList) {
        arr.push(item.batchNo);
      }
      let obj = {
        batchNo: arr,
        groupCode: ProcessList[1].split("_")[0],
        groupName: ProcessList[1].split("_")[1],
        procedureCode: BatchNoList,
        userId: localStorage.getItem("userId"),
      };

      console.log(GroupList, BatchNoList, ProcessList, obj);
      // 提交派工
      // ProductionOrderService.addWorkOrderDispatch(obj).then(res => {
      //   this.setState({ btnLoading: false });
      //   if (res.data.code !== 200) {
      //     openModalMessage('warning', res.data.msg);
      //     return;
      //   }
      //   const that = this;
      //   Modal.confirm({
      //     title: res.data.msg,
      //     okText: '继续操作',
      //     cancelText: '关闭',
      //     icon: <Icon type="check-circle" theme="twoTone" twoToneColor="#52c41a" />,
      //     centered: true,
      //     onOk() { },
      //     onCancel() {
      //       that.handleCancel();
      //       that.setState({ GroupList: [], ProcessList: [], BatchNoList: [] })
      //     },
      //   });
      // }).catch(err => {
      //   this.setState({ btnLoading: false });
      //   openModalMessage('error', err.message)
      // })
    });
  };
  //开工
  submitMenu_kaigong = () => {
    this.formAdd_kaigong.validateFields((err, value) => {
      if (err) return;
      this.setState({ btnLoading: true });
      const { GroupList, BatchNoList, kaigong_type } = this.state;
      if (!GroupList.length) {
        this.setState({ btnLoading: false });
        openModalMessage("warning", "请选择批号！");
        return;
      }
      if (!BatchNoList.length) {
        this.setState({ btnLoading: false });
        openModalMessage("warning", "请选择工序！");
        return;
      }

      let arr = [];
      for (var item of GroupList) {
        arr.push(item.batchNo);
      }
      let obj = {
        batchNo: arr,
        procedureCode: [...BatchNoList],
        userId: localStorage.getItem("userId"),
        department: localStorage.getItem("workShop"),
      };

      // console.log(GroupList, BatchNoList, kaigong_type, obj);

      // kaigong_type   0   开工
      if (kaigong_type === 0) {
        ProductionOrderService.addWorkOrderStart(obj)
          .then((res) => {
            this.setState({ btnLoading: false });
            if (res.data.code !== 200) {
              openModalMessage("warning", res.data.msg);
              return;
            }
            const that = this;
            Modal.confirm({
              title: res.data.msg,
              okText: "继续操作",
              cancelText: "关闭",
              icon: (
                <Icon
                  type="check-circle"
                  theme="twoTone"
                  twoToneColor="#52c41a"
                />
              ),
              centered: true,
              onOk() {},
              onCancel() {
                that.handleCancel();
                that.setState({
                  GroupList: [],
                  ProcessList: [],
                  BatchNoList: [],
                });
              },
            });
          })
          .catch((err) => {
            this.setState({ btnLoading: false });
            openModalMessage("error", err.message);
          });
      }
      // kaigong_type   1   报工
      else if (kaigong_type === 1) {
        ProductionOrderService.addWorkOrderReport(obj)
          .then((res) => {
            this.setState({ btnLoading: false });
            if (res.data.code !== 200) {
              openModalMessage("warning", res.data.msg);
              return;
            }
            const that = this;
            Modal.confirm({
              title: res.data.msg,
              okText: "继续操作",
              cancelText: "关闭",
              icon: (
                <Icon
                  type="check-circle"
                  theme="twoTone"
                  twoToneColor="#52c41a"
                />
              ),
              centered: true,
              onOk() {},
              onCancel() {
                that.handleCancel();
                that.setState({
                  GroupList: [],
                  ProcessList: [],
                  BatchNoList: [],
                });
              },
            });
          })
          .catch((err) => {
            this.setState({ btnLoading: false });
            openModalMessage("error", err.message);
          });
      }
    });
  };
  paigong = (record) => {
    this.setState({ visible_paigong: true, paigongData: record });
  };
  quxiaopaigong = (record) => {
    let str = `userId=${localStorage.getItem("userId")}&workUniqueType=${
      record.workUniqueType
    }`;
    let that = this;
    Modal.confirm({
      title: `【${record.batchNo}-${record.procedureName}】是否取消派工？`,
      onOk: async () => {
        await ProductionOrderService.updateCancelDispatch(str)
          .then((res) => {
            if (res.data.code !== 200) {
              openModalMessage("warning", res.data.msg);
              return;
            }
            openSuccessModal(res.data.msg);
            that.handleCancel();
          })
          .catch((err) => {
            openModalMessage("error", err.message);
          });
      },
      onCancel() {},
    });
  };
  kaigong = (record) => {
    const that = this;
    // const arr = [
    //   {
    //     "batchNo": record.batchNo,
    //     "workSequenceList": [
    //       record.procedureName
    //     ]
    //   }
    // ]

    let obj = {
      batchNo: [record.batchNo],
      procedureCode: [record.procedureCode],
      userId: localStorage.getItem("userId"),
      department: localStorage.getItem("workShop"),
    };
    Modal.confirm({
      title: "确认进行开工吗？",
      onOk: async () => {
        await ProductionOrderService.addWorkOrderStart(obj)
          .then((res) => {
            if (res.data.code !== 200) {
              openModalMessage("warning", res.data.msg);
              return;
            }
            openSuccessModal(res.data.msg);
            that.handleCancel();
            that.setState({ GroupList: [], ProcessList: [], BatchNoList: [] });
          })
          .catch((err) => {
            openModalMessage("error", err.message);
          });
      },
      onCancel() {},
    });
  };

  baogong = (record) => {
    const that = this;
    // const arr = [
    //   {
    //     "batchNo": record.batchNo,
    //     "workSequenceList": [
    //       record.procedureName
    //     ]
    //   }
    // ]
    let obj = {
      batchNo: [record.batchNo],
      procedureCode: [record.procedureCode],
      userId: localStorage.getItem("userId"),
      department: localStorage.getItem("workShop"),
    };
    Modal.confirm({
      title: "确认进行报工吗？",
      onOk: async () => {
        await ProductionOrderService.addWorkOrderReport(obj)
          .then((res) => {
            if (res.data.code !== 200) {
              openModalMessage("warning", res.data.msg);
              return;
            }
            openSuccessModal(res.data.msg);
            that.handleCancel();
            that.setState({ GroupList: [], ProcessList: [], BatchNoList: [] });
          })
          .catch((err) => {
            openModalMessage("error", err.message);
          });
      },
      onCancel() {},
    });
  };
  submit_paigong = () => {
    this.form_paigong.validateFields((err, value) => {
      if (err) return;
      console.log(value);
      const { paigongData } = this.state;
      // if (value.groupList.length === 2) {
      //   paigongData.groupCode = value.groupList[1]
      // }
      // paigongData.workSequence = paigongData.procedureName

      let obj = {
        batchNo: [paigongData.batchNo],
        groupCode: value.groupList[1].split("_")[0],
        groupName: value.groupList[1].split("_")[1],
        procedureCode: [paigongData.procedureCode],
        userId: localStorage.getItem("userId"),
      };
      ProductionOrderService.addWorkOrderDispatch(obj)
        .then((res) => {
          this.setState({ btnLoading: false });
          if (res.data.code !== 200) {
            openModalMessage("warning", res.data.msg);
            return;
          }
          openSuccessModal(res.data.msg);
          this.handleCancel();
        })
        .catch((err) => {
          this.setState({ btnLoading: false });
          openModalMessage("error", err.message);
        });
    });
  };
  onHandleOk = () => {
    this.formDrawer.validateFields((err, value) => {
      if (err) return;
      console.log(value);
    });
  };
  onHandleOk1 = () => {
    this.formDrawer1.validateFields((err, value) => {
      if (err) return;
      console.log(value);
    });
  };
  //0新增  1修改
  create = () => {
    const { selectedRows } = this.state;
    if (!selectedRows || !selectedRows.length) {
      openModalMessage("warning", "请选择要派工的单据！");
      return;
    }
    console.log(selectedRows, "selectedRows");
    this.setState({
      visible: true,
      AssignProductionOrderList: selectedRows,
    });
  };
  showDrawer = () => {
    this.setState({
      drawerVisible: true,
    });
  };
  showDrawer1 = () => {
    this.setState({
      drawerVisible1: true,
    });
  };

  handleCancel = (e) => {
    this.formAdd && this.formAdd.resetFields();
    this.formAdd_kaigong && this.formAdd_kaigong.resetFields();
    this.formChooseBill && this.formChooseBill.resetFields();
    this.formPassToStock && this.formPassToStock.resetFields();
    this.formDrawer && this.formDrawer.resetFields();
    this.formDrawer1 && this.formDrawer1.resetFields();
    this.form_paigong && this.form_paigong.resetFields();
    this.setState({
      visible: false,
      btnDrawer: false,
      drawerVisible: false,
      drawerVisible1: false,
      visibleChooseBill: false,
      visiblePassToStock: false,
      visible_kaigong: false,
      visible_shiji: false,
      visible_zhijian: false,
      visible_ruku: false,
      visible_paigong: false,
      // row: [],
      selectedRowKeys: [],
      selectedRowKeysChild: [],
      selectedRows: [],
      selectedRowsChild: [],
      dataSource_shiji: [],
      dataSource_zhijian: [],
      paigongData: {},
    });
    this.fetch();

    // 展开并请求展开后的数据
    this.state.row.length > 0 &&
      this.onExpand(true, { batchNo: this.state.row[0] });
  };

  handleSearch = (value) => {
    // console.log(value)
    if (value.assembleStartDate && value.assembleStartDate.length === 2) {
      value.assembleStartDateMin = value.assembleStartDate[0].format(
        "YYYY-MM-DD 00:00:00"
      );
      value.assembleStartDateMax = value.assembleStartDate[1].format(
        "YYYY-MM-DD 23:59:59"
      );
      delete value.assembleStartDate;
    }
    if (value.firstDeliveryDate && value.firstDeliveryDate.length === 2) {
      value.firstDeliveryDateMin = value.firstDeliveryDate[0].format(
        "YYYY-MM-DD 00:00:00"
      );
      value.firstDeliveryDateMax = value.firstDeliveryDate[1].format(
        "YYYY-MM-DD 23:59:59"
      );
      delete value.firstDeliveryDate;
    }
    this.setState({ searchItem: value }, this.fetch);
  };

  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced });
  };
  loadData = (value, dataSource) => {
    console.log(value, dataSource);
  };
  // 选择某一行数据
  chooseRow = (record) => {
    let flag = true;
    let index = 0;
    this.state.selectedRowKeys.forEach((row, i) => {
      if (row === record.batchNo) {
        flag = false;
        index = i;
      }
    });
    const selectedRowKeys = this.state.selectedRowKeys;
    const selectedRows = this.state.selectedRows;
    if (flag) {
      selectedRowKeys.push(record.batchNo);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({
      selectedRowKeys: selectedRowKeys,
      selectedRows: selectedRows,
    });
  };
  // 选择某一行数据
  chooseRowChild = (record) => {
    const { detailList } = this.state;
    let flag = true;
    let index = 0;
    this.state.selectedRowKeysChild.forEach((row, i) => {
      if (row === record.workUniqueType) {
        flag = false;
        index = i;
      }
    });
    const selectedRowKeys = this.state.selectedRowKeysChild;
    const selectedRows = this.state.selectedRowsChild;
    if (flag) {
      selectedRowKeys.push(record.workUniqueType);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({
      selectedRowKeysChild: selectedRowKeys,
      selectedRowsChild: selectedRows,
    });
  };
  // 展开方法
  onExpand = (expanded, record) => {
    this.setState({ loading: true });
    const that = this;
    console.log(expanded, record, "record------");
    // const { row } = this.state
    // let batchNo = row.length > 0 ? row[0] : ''
    // console.log(batchNo, row, '------')
    // if (batchNo == record.batchNo) {
    //   expanded = false
    // }

    if (expanded) {
      let obj = {
        ...this.state.searchItem,
        ...record,
        pageSize: 1000,
        pageNum: 1,
      };
      // console.log(obj, 'obj------');
      // const searchTerm = { ...that.state.searchTerm };
      // searchTerm.productionNum = record.productionNum;
      ProductionOrderService.findPlanDetailsAll(obj).then((res) => {
        console.log(res, "findPlanDetailsAll");
        this.setState({
          detailList: res.data.data,
          row: [record.batchNo],
          expandedData: record,
          loading: false,
        });
      });
    } else {
      this.setState({
        row: [],
        loading: false,
      });
    }
  };
  /***
   * 开工、报工
   */
  startWork = (type) => {
    if (type === 0) {
      const { selectedRows } = this.state;
      if (!selectedRows || !selectedRows.length) {
        openModalMessage("warning", "请选择要开工的单据！");
        return;
      }
      this.setState({
        AssignProductionOrderList_kaigong: selectedRows,
        visible_kaigong: true,
        drawerTitle_kaigong: "开工",
        kaigong_type: type,
      });
    } else if (type === 1) {
      const { selectedRows } = this.state;
      if (!selectedRows || !selectedRows.length) {
        openModalMessage("warning", "请选择要报工的单据！");
        return;
      }
      this.setState({
        AssignProductionOrderList_kaigong: selectedRows,
        visible_kaigong: true,
        drawerTitle_kaigong: "报工",
        kaigong_type: type,
      });
    }
  };
  /***
   * 报工
   */
  reportWork = () => {
    Modal.confirm({
      title: "报工",
      content: "选中的生产订单即将报工",
      okText: "确认",
      cancelText: "取消",
    });
  };
  chooseBill = () => {
    this.setState({ visibleChooseBill: true });
  };
  submitChooseBill = () => {
    this.formChooseBill.validateFields((err, value) => {
      if (err) return;
      console.log(value);
    });
  };

  passToStock = () => {
    this.setState({ visiblePassToStock: true });
  };
  submitPassToStock = () => {
    this.formPassToStock.validateFields((err, value) => {
      if (err) return;
      console.log(value);
    });
  };
  saveAddFormList = (type, value) => {
    if (type === 1) {
      this.setState({ GroupList: value });
      return;
    }
    if (type === 2) {
      this.setState({ BatchNoList: value });
      return;
    }
    if (type === 3) {
      this.setState({ ProcessList: value });
      return;
    }
  };
  // 打开申请试机弹窗
  create_shiji = () => {
    const { selectedRows } = this.state;
    if (!selectedRows || !selectedRows.length) {
      openModalMessage("warning", "请选择要申请试机的数据！");
      return;
    }
    const arr = selectedRows.map((item) => item.batchNo);
    this.setState({ formData_shiji: { batchNo: arr } }, () =>
      setTimeout(() => {
        this.setState({ visible_shiji: true });
      })
    );
  };
  saveList_shiji = (data) => {
    this.setState({ dataSource_shiji: data });
  };
  submitMenu_shiji = () => {
    const { dataSource_shiji } = this.state;
    if (!dataSource_shiji.length) {
      openModalMessage("warning", "请选择要申请试机的数据！");
      return;
    }
    const that = this;
    for (var item of dataSource_shiji) {
      if (item.assembleProcess !== "100%") {
        Modal.confirm({
          title: "存在未完成装配的批号，继续提交吗？",
          centered: true,
          okText: "取消",
          cancelText: "继续提交",
          onOk() {
            return;
          },
          onCancel: async () => {
            await that.startShiJi();
          },
        });
        return;
      }
    }
    that.startShiJi();
  };
  startShiJi = async () => {
    const { dataSource_shiji } = this.state;
    console.log(dataSource_shiji);
    let obj = {},
      batchNo = [];
    for (var item of dataSource_shiji) {
      // item.applyUserId = localStorage.getItem('userId');
      batchNo.push(item.batchNo);
    }
    obj = {
      batchNo,
      userId: localStorage.getItem("userId"),
    };
    console.log(obj, "obj");

    await ProductionOrderService.addWorkOrderMachine(obj).then((res) => {
      console.log(res);
      if (res.data.code !== 200) {
        openModalMessage("warning", res.data.msg);
        return;
      }
      const that = this;
      // const number = dataSource_shiji.length
      // const str = dataSource_shiji && dataSource_shiji.map(item)=>
      Modal.confirm({
        title: `确定推送吗？`,
        centered: true,
        onOk: async () => {
          let obj = {
            whether: 1,
            title: "申请试机消息推送",
            // "text": ` * 机型  | 批号  | 装配车间 | 装配机位 | 装配进度 | \n ${dataSource_shiji && dataSource_shiji.map(item => ` \n * ${item.model} | ${item.batchNo} | ${item.department} | ${item.stationId} | ${item.assembleProcess} | \n`)}
            text: ` * 机型  | 批号  | 装配车间 | 装配进度 | \n ${
              dataSource_shiji &&
              dataSource_shiji.map(
                (item) =>
                  ` \n * ${item.model} | ${item.batchNo} | ${item.department} | ${item.assembleProcess} | \n`
              )
            } 
             \n * 正在进行试机 `,
            functionName: "试机申请推送",
          };
          await DingTalkSettingsService.dingPushNews(obj)
            .then((res) => {
              if (res.data.code !== 200) {
                openModalMessage("warning", res.data.msg);
                return;
              }
              openSuccessModal(res.data.msg);
              that.handleCancel();
            })
            .catch((err) => {
              openModalMessage("error", err.message);
            });
        },
        onCancel() {},
      });
    });
  };
  // 打开申请质检弹窗
  create_zhijian = () => {
    const { selectedRows } = this.state;
    if (!selectedRows || !selectedRows.length) {
      openModalMessage("warning", "请选择要申请质检的数据！");
      return;
    }
    const arr = selectedRows.map((item) => item.batchNo);
    this.setState({ formData_zhijian: { batchNoList: arr } }, () =>
      setTimeout(() => {
        this.setState({ visible_zhijian: true });
      })
    );
  };
  saveList_zhijian = (data) => {
    this.setState({ dataSource_zhijian: data });
  };
  submitMenu_zhijian = () => {
    const { dataSource_zhijian } = this.state;
    if (!dataSource_zhijian.length) {
      openModalMessage("warning", "请选择要申请质检的数据！");
      return;
    }
    const that = this;
    for (var item of dataSource_zhijian) {
      if (item.testMachineProcess !== "100%") {
        Modal.confirm({
          title: "存在试机未完成的的批号，继续提交吗？",
          centered: true,
          okText: "取消",
          cancelText: "继续提交",
          onOk() {
            return;
          },
          onCancel: async () => {
            await that.startZhiJian();
          },
        });
        return;
      }
    }
    that.startZhiJian();
  };
  startZhiJian = async () => {
    const { dataSource_zhijian } = this.state;
    console.log(dataSource_zhijian);
    let obj = {},
      batchNo = [];
    for (var item of dataSource_zhijian) {
      item.applyUserId = localStorage.getItem("userId");
      batchNo.push(item.batchNo);
    }
    obj = {
      batchNo,
      userId: localStorage.getItem("userId"),
    };
    console.log(obj, "obj");
    await ProductionOrderService.addWorkOrderCheck(obj).then((res) => {
      console.log(res);
      if (res.data.code !== 200) {
        openModalMessage("warning", res.data.msg);
        return;
      }
      const that = this;
      // const number = dataSource_shiji.length
      // const str = dataSource_shiji && dataSource_shiji.map(item)=>
      Modal.confirm({
        title: `确定推送吗？`,
        centered: true,
        onOk: async () => {
          let obj = {
            whether: 1,
            title: "质检申请消息推送",
            // "text": ` * 机型  | 批号  | 装配车间 | 装配机位 | 装配进度 | 试机进度 | \n ${dataSource_zhijian && dataSource_zhijian.map(item => ` \n * ${item.model} | ${item.batchNo} | ${item.department} | ${item.stationId} | ${item.assembleProcess} | ${item.testMachineProcess} | \n`)}
            text: ` * 机型  | 批号  | 装配车间 | 装配进度 | 试机进度 | \n ${
              dataSource_zhijian &&
              dataSource_zhijian.map(
                (item) =>
                  ` \n * ${item.model} | ${item.batchNo} | ${item.department} | ${item.assembleProcess} | ${item.testMachineProcess} | \n`
              )
            } 
             \n * 正在进行质检申请 `,
            functionName: "质检申请推送",
          };
          await DingTalkSettingsService.dingPushNews(obj)
            .then((res) => {
              if (res.data.code !== 200) {
                openModalMessage("warning", res.data.msg);
                return;
              }
              openSuccessModal(res.data.msg);
              that.handleCancel();
            })
            .catch((err) => {
              openModalMessage("error", err.message);
            });
        },
        onCancel() {},
      });
    });
  };

  // 打开申请入库弹窗
  create_ruku = () => {
    const { selectedRows } = this.state;
    if (!selectedRows || !selectedRows.length) {
      openModalMessage("warning", "请选择要申请入库的数据！");
      return;
    }
    const arr = selectedRows.map((item) => item.batchNo);
    this.setState({ formData_ruku: { batchNoList: arr } }, () =>
      setTimeout(() => {
        this.setState({ visible_ruku: true });
      })
    );
  };
  saveList_ruku = (data) => {
    this.setState({ dataSource_ruku: data });
  };
  submitMenu_ruku = () => {
    const { dataSource_ruku } = this.state;
    if (!dataSource_ruku.length) {
      openModalMessage("warning", "请选择要申请入库的数据！");
      return;
    }
    const that = this;
    for (var item of dataSource_ruku) {
      if (item.status !== "已完成") {
        Modal.confirm({
          title: "存在装配/试机/质检未完成的的批号，继续提交吗？",
          centered: true,
          okText: "取消",
          cancelText: "继续提交",
          onOk() {
            return;
          },
          onCancel: async () => {
            await that.startRuku();
          },
        });
        return;
      }
    }
    that.startRuku();
  };
  startRuku = async () => {
    const { dataSource_ruku } = this.state;
    console.log(dataSource_ruku);
    for (var item of dataSource_ruku) {
      item.applyUserId = localStorage.getItem("userId");
    }
    await ProductionOrderService.applyEnterWarehouse(dataSource_ruku).then(
      (res) => {
        console.log(res);
        if (res.data.code !== 200) {
          openModalMessage("warning", res.data.msg);
          return;
        }
        const that = this;
        // const number = dataSource_shiji.length
        // const str = dataSource_shiji && dataSource_shiji.map(item)=>
        Modal.confirm({
          title: `确定推送吗？`,
          centered: true,
          onOk: async () => {
            let obj = {
              whether: 1,
              title: "入库申请消息推送",
              // "text": ` * 机型  | 批号  | 装配车间 | 装配机位 | 装配进度 | 试机进度 |  质检进度 |  状态 |  \n ${dataSource_ruku && dataSource_ruku.map(item => ` \n * ${item.model} | ${item.batchNo} | ${item.department} | ${item.stationId} | ${item.assembleProcess} | ${item.testMachineProcess} |  ${item.qualityCheckProcess} |  ${item.isStates} |  \n`)}
              text: ` * 机型  | 批号  | 装配车间 | 装配进度 | 试机进度 |  质检进度 |  状态 |  \n ${
                dataSource_ruku &&
                dataSource_ruku.map(
                  (item) =>
                    ` \n * ${item.model} | ${item.batchNo} | ${item.department} | ${item.assembleProcess} | ${item.testMachineProcess} |  ${item.qualityCheckProcess} |  ${item.isStates} |  \n`
                )
              } 
             \n * 正在进行入库申请 `,
              functionName: "入库申请推送",
            };
            await DingTalkSettingsService.dingPushNews(obj)
              .then((res) => {
                if (res.data.code !== 200) {
                  openModalMessage("warning", res.data.msg);
                  return;
                }
                openSuccessModal(res.data.msg);
                that.handleCancel();
              })
              .catch((err) => {
                openModalMessage("error", err.message);
              });
          },
          onCancel() {},
        });
      }
    );
  };
  downloadFather = () => {
    const { selectedRows } = this.state;
    if (selectedRows.length) {
      this.setState({ downloadLoading: true });
      ProductionOrderService.exportProductionOrderParentExcel({
        dtoList: selectedRows,
      }).then((res) => {
        //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
        let url = window.URL.createObjectURL(
          new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          })
        );
        // 创建A标签
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        // 设置的下载文件文件名
        const fileName = decodeURI("生产订单管理（父表）");
        // 触发点击方法
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        this.setState({ downloadLoading: false });
      });
    } else {
      Modal.confirm({
        title: "默认导出数据较多，需要较长时间，确认全部导出吗？",
        onOk: async () => {
          await this.fetchAll();
          const { dataSourceAll } = this.state;
          await ProductionOrderService.exportProductionOrderParentExcel({
            dtoList: dataSourceAll,
          }).then((res) => {
            //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
            let url = window.URL.createObjectURL(
              new Blob([res.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              })
            );
            // 创建A标签
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            // 设置的下载文件文件名
            const fileName = decodeURI("生产订单管理（父表）");
            // 触发点击方法
            link.setAttribute("download", fileName);
            document.body.appendChild(link);
            link.click();
            this.setState({ downloadLoading: false });
          });
        },
        onCancel() {},
      });
    }
  };
  downloadSon = () => {
    const { selectedRowsChild } = this.state;
    if (selectedRowsChild.length) {
      this.setState({ downloadLoadingSon: true });
      ProductionOrderService.exportProductionOrderChildExcel({
        dtoList: selectedRowsChild,
      }).then((res) => {
        //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
        let url = window.URL.createObjectURL(
          new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          })
        );
        // 创建A标签
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        // 设置的下载文件文件名
        const fileName = decodeURI("生产订单管理（子表）");
        // 触发点击方法
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        this.setState({ downloadLoadingSon: false });
      });
    } else {
      openModalMessage("warning", "请选择需要导出的子表数据");
      return;
    }
    //  else {
    //   Modal.confirm({
    //     title: '默认导出数据较多，需要较长时间，确认全部导出吗？',
    //     onOk: async () => {
    //       await this.fetchAll();
    //       const { dataSourceAll } = this.state;
    //       await ProductionOrderService.exportProductionOrderChildExcel({ dtoList: dataSourceAll }).then(res => {
    //         //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
    //         let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
    //         // 创建A标签
    //         let link = document.createElement('a')
    //         link.style.display = 'none'
    //         link.href = url
    //         // 设置的下载文件文件名
    //         const fileName = decodeURI('生产订单管理（子表）');
    //         // 触发点击方法
    //         link.setAttribute('download', fileName)
    //         document.body.appendChild(link)
    //         link.click()
    //         this.setState({ downloadLoading: false })
    //       })
    //     },
    //     onCancel() { }
    //   })
    // }
  };
  fetchAll = async () => {
    const { searchItem, total } = this.state;
    searchItem.pageNum = 1;
    searchItem.pageSize = total;
    await ProductionOrderService.findPlanAll(searchItem)
      .then((res) => {
        if (res.data.data.code !== 200) {
          openModalMessage("warning", res.data.data.msg);
          return;
        }
        const dataSourceAll = res.data.data.data;
        const selectedRowKeys = dataSourceAll.map((item) => item.batchNo);
        this.setState({
          dataSourceAll,
          selectedRowKeys,
          selectedRows: dataSourceAll,
        });
      })
      .catch((err) => {
        openModalMessage("error", err.message);
      });
  };
  // 跳转特供信息
  openTGXX = (record) => {
    const { searchItem } = this.state;
    const data = {};
    data.batchNo = record.batchNo;
    data.procedureName = record.procedureName;
    data.procedureCode = record.procedureCode;
    localStorage.setItem(
      "SpecialMachine_searchItem",
      JSON.stringify(searchItem)
    );
    localStorage.setItem("SpecialMachine_detailsList", JSON.stringify(data));
    this.props.history.push({
      pathname: "/SpecialMachine",
      data: { ...data, ...searchItem },
    });
  };
  // 跳转图纸检索
  openTZJS = (record) => {
    const { searchItem } = this.state;
    const data = {};
    data.batchNo = record.batchNo;
    data.procedureName = record.procedureName;
    data.procedureCode = record.procedureCode;
    localStorage.setItem(
      "DrawingRetrieval_searchItem",
      JSON.stringify(searchItem)
    );
    localStorage.setItem("DrawingRetrieval_detailsList", JSON.stringify(data));
    this.props.history.push({
      pathname: "/DrawingRetrieval",
      data: { ...data, ...searchItem },
    });
  };

  // 打开详情页
  openDetails = (record) => {
    const { searchItem } = this.state;
    const data = {};
    data.batchNo = record.batchNo;
    data.procedureName = record.procedureName;
    data.procedureCode = record.procedureCode;
    localStorage.setItem(
      "productionOrder_searchItem",
      JSON.stringify(searchItem)
    );
    localStorage.setItem("productionOrder_detailsList", JSON.stringify(data));
    this.props.history.push({
      pathname: "/productionOrder_Details",
      data: { record: data, searchItem },
    });
  };
  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState(
      {
        searchItem: {
          department: localStorage.getItem("workShop"),
        },
      },
      this.fetch
    );
  };
  render() {
    const {
      formData1,
      options,
      addFrom,
      loading,
      dataSource,
      formData,
      visible,
      modalTitle,
      drawerVisible,
      drawerTitle,
      drawerVisible1,
      advanced,
      columns,
      pageNum,
      pageSize,
      total,
      selectedRowKeys,
      selectedRowKeysChild,
      visibleChooseBill,
      visiblePassToStock,
      visible_kaigong,
      drawerTitle_kaigong,
      AssignProductionOrderList,
      AssignProductionOrderList_kaigong,
      kaigong_type,
      btnLoading,
      visible_shiji,
      formData_shiji,
      selectedRows,
      formData_zhijian,
      visible_zhijian,
      formData_ruku,
      visible_ruku,
      visible_paigong,
      downloadLoading,
      downloadLoadingSon,
      searchItem,
      statusList,
      workStatusList,
    } = this.state;
    const rowSelection = {
      type: "checkbox",
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        });
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [...this.state.selectedRowKeys];
        const rows = [...this.state.selectedRows];
        if (selected) {
          changeRows.forEach((row) => {
            if (isInvalidObject(keys.find((key) => key === row.batchNo))) {
              keys.push(row.batchNo);
              rows.push(row);
            }
          });
        } else {
          changeRows.forEach((row) => {
            keys.splice(keys.indexOf(row.batchNo), 1);
            rows.splice(rows.indexOf(row), 1);
          });
        }
        this.setState({ selectedRows: rows, selectedRowKeys: keys });
      },
    };
    const rowSelectionChild = {
      type: "checkbox",
      selectedRowKeys: selectedRowKeysChild,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRowsChild: selectedRows,
          selectedRowKeysChild: selectedRowKeys,
        });
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [...this.state.selectedRowKeysChild];
        const rows = [...this.state.selectedRowsChild];
        if (selected) {
          changeRows.forEach((row) => {
            if (
              isInvalidObject(keys.find((key) => key === row.workUniqueType))
            ) {
              keys.push(row.workUniqueType);
              rows.push(row);
            }
          });
        } else {
          changeRows.forEach((row) => {
            keys.splice(keys.indexOf(row.workUniqueType), 1);
            rows.splice(rows.indexOf(row), 1);
          });
        }
        this.setState({ selectedRowsChild: rows, selectedRowKeysChild: keys });
      },
    };
    const expandedRowRender = () => {
      const { childColumns } = this.state;
      return (
        <TableCustomize
          onRow={(record, rowKey) => ({
            // onClick: this.chooseRowChild.bind(this, record, rowKey)
          })}
          rowSelection={rowSelectionChild}
          allowDrafting={true}
          allowRowEdit
          dataSource={this.state.detailList}
          columns={childColumns}
          pagination={false}
          scroll={{ y: 300 }}
          rowKey={(record) => record.workUniqueType}
          rowClassName={(record, index) => {
            return [
              "editable-row",
              index % 2 === 0 ? "editable-row" : "editable-row12",
            ];
          }}
        />
      );
    };
    return (
      <div>
        <BasicLayoutSearch>
          <SearchForm
            onSearch={this.handleSearch}
            onClick={this.onHandleAdvanced}
            advanced={advanced}
            searchItem={searchItem}
            statusList={statusList}
            workStatusList={workStatusList}
            addFrom={addFrom}
            formData1={formData1}
            resetForm={this.resetForm}
            ref={(node) => (this.formSearch = node)}
          />
        </BasicLayoutSearch>
        <BasicLayout
          buttons={[
            <RefreshButton
              key={1}
              onClick={this.updateBatchRefresh}
              icon="sync"
            />,
            <CheckAllButton key={2} onClick={this.fetchAll} icon="plus" />,
            <PGButton key={3} onClick={this.create} />,
            <KGButton key={4} onClick={() => this.startWork(0)} />,
            <BGButton key={5} onClick={() => this.startWork(1)} />,
            <SJButton key={6} onClick={this.create_shiji} />,
            <ZJButton key={7} onClick={this.create_zhijian} />,
            <RKButton key={8} onClick={this.create_ruku} />,
            <DownLoadButton
              key={9}
              onClick={this.downloadFather}
              text="导出（父表）"
              icon="download"
            />,
            <DownLoadButton
              key={10}
              onClick={this.downloadSon}
              text="导出（子表）"
              icon="download"
            />,

            // <Button key={10} type="primary" onClick={() => this.updateBatchRefresh()} icon="redo">进度刷新</Button>,
            // // <Button key={9} type="primary" onClick={() => this.fetch()} icon="redo">刷新</Button>,
            // <Button key={0} type="primary" onClick={this.fetchAll} icon="plus">跨页全选</Button>,
            // <Button key={1} type="primary" onClick={this.create} icon="plus">派工</Button>,
            // <Button key={2} onClick={() => this.startWork(0)} type="primary" icon="minus">开工</Button>,
            // <Button key={3} onClick={() => this.startWork(1)} type="primary" icon="upload">报工</Button>,
            // <Button type="primary" key={4} onClick={() => { this.create_shiji() }} icon="upload">申请试机</Button>,
            // <Button type="primary" key={5} onClick={() => { this.create_zhijian() }} icon="plus">申请质检</Button>,
            // <Button type="primary" key={6} onClick={() => { this.create_ruku() }} icon="minus">申请入库</Button>,
            // <Button type="primary" key={7} onClick={() => { this.downloadFather() }} icon="download" loading={downloadLoading}>导出（父表）</Button>,
            // <Button type="primary" key={8} onClick={() => { this.downloadSon() }} icon="download" loading={downloadLoadingSon}>导出（子表）</Button>,
          ]}
          name="生产订单管理"
          icon="table"
        >
          <Alert
            message={
              <div>
                已选择
                <span style={{ color: "#fd1818", margin: "0 3px" }}>
                  {selectedRowKeys.length}
                </span>
                项
              </div>
            }
            type="info"
            showIcon
            style={{ marginBottom: 15 }}
          />
          <TableCustomize
            columns={columns}
            rowKey={(record) => record.batchNo}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            allowDrafting={true}
            allowRowEdit
            allowEditable={this.loadData}
            rowSelection={rowSelection}
            rowClassName={(record, index) => {
              return [
                "editable-row",
                index % 2 === 0 ? "editable-row" : "editable-row12",
              ];
            }}
            expandRowByClick={true} // 通过点击行来展开子行
            // onRow={(record, rowKey) => ({
            //   // onClick: this.chooseRow.bind(this, record, rowKey),  // 点击行选中
            //   onClick: this.onExpand.bind(this, true, record),  // 点击行展开子表
            //   // onClick: () => {
            //   //   this.onExpand(true, record)
            //   //   this.chooseRow(record, rowKey)
            //   // }
            // })}
            expandedRowKeys={this.state.row}
            expandedRowRender={expandedRowRender}
            onExpand={(expanded, record) => this.onExpand(expanded, record)}
          />
          <BasicPagination
            pageNum={pageNum}
            pageSize={pageSize}
            total={total}
            loadData={this.fetch}
          />
        </BasicLayout>
        {/* 派工 */}
        <Modal
          visible={visible}
          destroyOnClose
          title={modalTitle}
          onOk={this.submitMenu}
          onCancel={this.handleCancel}
          okText="执行派工"
          cancelText="取消"
          width={"70%"}
          maskClosable={false}
          confirmLoading={btnLoading}
        >
          <AddForm
            ref={(node) => (this.formAdd = node)}
            AssignProductionOrderList={AssignProductionOrderList}
            formData1={formData1}
            options={options}
            addFrom={addFrom}
            onSaveAddFormList={this.saveAddFormList}
          />
        </Modal>

        {/* 开工 */}
        <Modal
          visible={visible_kaigong}
          destroyOnClose
          title={drawerTitle_kaigong}
          onOk={this.submitMenu_kaigong}
          onCancel={this.handleCancel}
          okText={kaigong_type === 0 ? "执行开工" : "执行报工"}
          cancelText="取消"
          width={"50%"}
          maskClosable={false}
          confirmLoading={btnLoading}
        >
          <AddForm1
            ref={(node) => (this.formAdd_kaigong = node)}
            AssignProductionOrderList={AssignProductionOrderList_kaigong}
            onSaveAddFormList={this.saveAddFormList}
            type={kaigong_type}
          />
        </Modal>

        {/* 申请试机 */}
        <Modal
          visible={visible_shiji}
          destroyOnClose
          title={"申请试机"}
          onOk={this.submitMenu_shiji}
          onCancel={this.handleCancel}
          okText={"申请试机"}
          cancelText="取消"
          width={"50%"}
          bodyStyle={{ maxHeight: "60vh" }}
          maskClosable={false}
          confirmLoading={btnLoading}
        >
          <AddForm2
            onSaveShiJiList={this.saveList_shiji}
            searchItem={formData_shiji}
            selectedRows={selectedRows}
          />
        </Modal>

        {/* 申请质检 */}
        <Modal
          visible={visible_zhijian}
          destroyOnClose
          title={"申请质检"}
          onOk={this.submitMenu_zhijian}
          onCancel={this.handleCancel}
          okText={"申请质检"}
          cancelText="取消"
          width={"50%"}
          bodyStyle={{ maxHeight: "60vh" }}
          maskClosable={false}
          confirmLoading={btnLoading}
        >
          <AddForm3
            onSaveShiJiList={this.saveList_zhijian}
            searchItem={formData_zhijian}
            selectedRows={selectedRows}
          />
        </Modal>
        {/* 申请入库 */}
        <Modal
          visible={visible_ruku}
          destroyOnClose
          title={"申请入库"}
          onOk={this.submitMenu_ruku}
          onCancel={this.handleCancel}
          okText={"申请入库"}
          cancelText="取消"
          width={"50%"}
          bodyStyle={{ maxHeight: "60vh" }}
          maskClosable={false}
          confirmLoading={btnLoading}
        >
          <AddForm4
            onSaveShiJiList={this.saveList_ruku}
            searchItem={formData_ruku}
            selectedRows={selectedRows}
          />
        </Modal>
        <Modal
          visible={visibleChooseBill}
          destroyOnClose
          title={"选择单据"}
          onOk={this.submitChooseBill}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
        >
          <ChooseBill
            ref={(node) => (this.formChooseBill = node)}
            formData={formData}
          />
        </Modal>

        {/* 单独派工 */}
        <Modal
          visible={visible_paigong}
          destroyOnClose
          title={"派工"}
          onOk={this.submit_paigong}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
        >
          <PaiGongForm
            ref={(node) => (this.form_paigong = node)}
            formData={formData}
          />
        </Modal>

        <Modal
          visible={visiblePassToStock}
          destroyOnClose
          title={"选择入库类型"}
          onOk={this.submitPassToStock}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
        >
          <PassToStock
            ref={(node) => (this.formPassToStock = node)}
            formData={formData}
          />
        </Modal>

        <Drawer
          width={400}
          visible={drawerVisible}
          title={drawerTitle}
          onClose={this.handleCancel}
        >
          <AddForm
            formData={formData}
            onOk={this.onHandleOk}
            ref={(node) => (this.formDrawer = node)}
            onClose={this.handleCancel}
          />
          <div
            style={{
              position: "absolute",
              right: 0,
              bottom: 0,
              width: "100%",
              borderTop: "1px solid #e9e9e9",
              padding: "10px 16px",
              background: "#fff",
              textAlign: "right",
            }}
          >
            <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>
              {"取消"}
            </Button>
            <Button type="primary" onClick={this.onHandleOk}>
              {"确认"}
            </Button>
          </div>
        </Drawer>

        <Drawer
          width={760}
          visible={drawerVisible1}
          title={drawerTitle}
          onClose={this.handleCancel}
        >
          <ProductionForm
            formData={formData}
            onOk={this.onHandleOk1}
            ref={(node) => (this.formDrawer1 = node)}
            onClose={this.handleCancel}
          />
          <div
            style={{
              position: "absolute",
              right: 0,
              bottom: 0,
              width: "100%",
              borderTop: "1px solid #e9e9e9",
              padding: "10px 16px",
              background: "#fff",
              textAlign: "right",
            }}
          >
            <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>
              {"取消"}
            </Button>
            <Button type="primary" onClick={this.onHandleOk}>
              {"确认"}
            </Button>
          </div>
        </Drawer>
      </div>
    );
  }
}
export default Form.create()(withRouter(ProductionOrder));
